<template>
  <BoTable ref="tableRef" :columns="columns" :request="_fetchList">
    <template #leftContainer>
      <div class="mr-4 w-48 border-r border-[rgba(255,255,255,.3)]">
        <div class="mr-2 flex h-10 items-center justify-between">
          <h3 class="module-title mb-0 mr-7">监测列表</h3>
        </div>
        <Tree
          :tree-data="treeData"
          :selected-keys="[selectKeys]"
          :expanded-keys="expandedKeys"
          :field-names="{ key: 'id', title: 'structureName' }"
        >
          <template #title="scope">
            <span @click="() => handleSelectStructure(scope)">{{
              scope.structureName
            }}</span>
          </template>
        </Tree>
      </div>
    </template>
  </BoTable>

  <Modal
    title="上传三维场景"
    v-model:open="visible"
    :mask-closable="false"
    :keyboard="false"
    destroy-on-close
    :footer="false"
  >
    <Upload3D
      @success="handleSuccess"
      :currentType="currentType"
      :fileItemId="fileItemId"
    />
  </Modal>
</template>

<route lang="json">
{
  "meta": {
    "title": "三维场景"
  }
}
</route>

<script setup lang="tsx">
import { computed, onMounted, ref, useTemplateRef } from 'vue';
import { useDicts } from '@boeyo/portal';
import { listToEnum, treeToArray } from '@boeyo/shared';
import { BoTable, BoTableProps } from '@boeyo/ui';
import { Modal, Tree, message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import {
  bindStructure,
  deleteFiles,
  fetchList,
  fetchStructureTree,
  projectSelectList,
  translate,
} from './api';
import Upload3D from './components/Upload3D.vue';

//
const router = useRouter();
const { sysSwitchingStateEnum } = useDicts(['sys_switching_state']);
const projectEnum = ref({});
const expandedKeys = ref([]);

onMounted(() => {
  projectSelectList().then((res) => {
    projectEnum.value = listToEnum(res.data, 'name', 'projectId');
  });
});

const treeData = ref();
onMounted(async () => {
  const result = await fetchStructureTree();
  treeData.value = result.data;
  expandedKeys.value = treeToArray(treeData.value).map((item) => item.id);
});

const _fetchList = (_params) => {
  return fetchList({ ...params, ..._params });
};

const selectKeys = ref(undefined);
const tableRef = useTemplateRef('tableRef');
let params: Record<string, any> = {};

const handleSelectStructure = (scope) => {
  const { monitoringType, id } = scope;
  params = {};
  if (id === selectKeys.value) {
    selectKeys.value = undefined;
  } else {
    selectKeys.value = id;
    switch (monitoringType) {
      case '1':
        params.netId = id;
        break;
      case '2':
        params.regionId = id;
        break;
      case '3':
        params.structureId = id;
        break;
    }
  }

  tableRef.value.refresh();
};

const columns = computed<BoTableProps['columns']>(() => {
  return [
    {
      title: '监测阵编号',
      dataIndex: 'monitoringCode',
    },
    {
      title: '监测阵名称',
      dataIndex: 'structureName',
    },
    {
      title: '关联项目',
      dataIndex: 'projectName',
      hideInSearch: true,
      // valueType: 'select',
      // valueEnum: projectEnum.value,
    },
    {
      title: '测点数量',
      dataIndex: 'pointCount',
      hideInSearch: true,
    },
    {
      title: '上传文件',
      dataIndex: 'fileName',
      hideInSearch: true,
      customRender: ({ record }) => {
        return record.fileName ? record.fileName : '-';
      },
    },
    {
      title: '转换状态',
      dataIndex: 'translate',
      hideInSearch: true,
      valueType: 'status',
      valueEnum: {
        ...sysSwitchingStateEnum.value,
      },
    },
    {
      title: '文件版本',
      dataIndex: 'fileVersion',
      hideInSearch: true,
      customRender: ({ record }) => {
        return record.fileVersion ? 'V' + record.fileVersion : '-';
      },
    },
    {
      title: '操作',
      hideInSearch: true,
      fixed: 'right',
      actions({ record }) {
        return [
          {
            text: '上传',
            hidden: record.fileVersion,
            onClick(record) {
              onUpload(record, 'upload');
            },
          },
          {
            text: '更新',
            hidden: !record.fileVersion,
            onClick(record) {
              onUpload(record, 'update');
            },
          },
          {
            text: '转换',
            hidden: !record.fileVersion || record.translate != 0,
            onClick(record) {
              onConversion(record);
            },
          },
          {
            text: '预览',
            hidden: record.translate != 2,
            onClick(record) {
              handlePreview(record);
            },
          },
          {
            text: '删除三维场景',
            hidden: !record.fileVersion,
            onClick(record) {
              Modal.confirm({
                title: '提示',
                content: '确认删除该场景的背景图及测点位置信息？',
                async onOk() {
                  await deleteFiles({
                    fileItemIds: [record.fileItemId],
                    structureId: record.structureId,
                  });
                  message.success('操作成功');
                  tableRef.value.refresh();
                },
              });
            },
          },
        ];
      },
    },
  ];
});

const visible = ref(false);
const currentId = ref();
const fileItemId = ref();
const currentType = ref();
const onUpload = async (record, type) => {
  fileItemId.value = record.fileItemId;
  currentId.value = record.structureId;
  currentType.value = type;
  visible.value = true;
};

const handlePreview = async (data) => {
  router.push({
    path: '/monitor/preview-3d',
    state: { ...data },
  });
};
const handleSuccess = async (data) => {
  await bindStructure({
    fileId: data.fileId,
    fileName: data.fileItemName,
    fileVersion: data.version,
    structureId: currentId.value,
    ...data,
  });
  visible.value = false;
  tableRef.value.search();
};

const onConversion = async (record) => {
  Modal.confirm({
    title: '提示',
    content: '确认开始进行模型转换吗?',
    async onOk() {
      await translate({ fileId: record.fileId });
      message.success('操作成功');
      tableRef.value.refresh();
    },
  });
};
</script>
